package concurrency2;

import java.util.concurrent.*;

public class ThreadDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        Thread t1 = new MyThread();
        t1.start();

        Thread t2 = new Thread(new MyThread2());
        t2.start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName());
        }).start();

        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();

        ExecutorService exec = Executors.newCachedThreadPool();

        Future<String> future = exec.submit(new Task());
        // 添加超时时间防止get方法长时间阻塞
        System.out.println("future.get() = " + future.get(5, TimeUnit.SECONDS));

        // FutureTask能够在高并发环境下确保任务只执行一次
        FutureTask<String> futureTask = new FutureTask<>(new Task());
        exec.submit(futureTask);
        System.out.println("futureTask.get() = " + futureTask.get(5, TimeUnit.SECONDS));
        exec.shutdown();
    }

}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

class MyThread2 implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

class Task implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return "call";
    }
}
